package com.hry.store.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.hry.store.common.Const;
import com.hry.store.common.ServerResponse;
import com.hry.store.pojo.User;
import com.hry.store.service.AlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

@Controller
public class PayController {
    private final static Logger logger = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private AlipayService alipayService;

    /**
     * 支付宝支付
     *
     * @param request
     * @param orderNo
     * @return
     */
    @RequestMapping("pay/alipay")
    @ResponseBody
    public ServerResponse alipay(HttpServletRequest request, @RequestParam("orderNo") Long orderNo) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "请先登陆");
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return alipayService.pay(user.getUserEmail(), orderNo, path);

    }

    /**
     * 支付宝回调方法
     */
    @RequestMapping("alipay_callback")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request) {
        Map<String, String> params = Maps.newHashMap();
        Map requestParam = request.getParameterMap();
        for (Iterator iterator = requestParam.keySet().iterator(); iterator.hasNext(); ) {
            String name = (String) iterator.next();
            String[] value = (String[]) requestParam.get(name);
            String valueStr = "";
            for (int i = 0; i < value.length; i++) {
                valueStr = (i == value.length - 1) ? valueStr + value[i] : valueStr + value[i] + ",";
            }
            params.put(name, valueStr);
        }
        logger.info("支付宝回调, sign:{}, trade_status:{}, 参数:{}", params.get("sign"), params.get("trade_status"), params.toString());
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if (!alipayRSACheckedV2) {
                return ServerResponse.createByErrorMessage("非法请求！！！");
            }

        } catch (AlipayApiException e) {
            logger.error("支付宝回调异常", e);
            e.printStackTrace();
        }
        ServerResponse serverResponse = alipayService.alipayCallback(params);
        if (serverResponse.isSuccess()) {

            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;
    }
}
